using System;
using UnityEngine;
using UnityEngine.UI;
using WorldMapBase;
using Yoozoo.Gameplay.City;
using Yoozoo.Modules.InnerCity.TouchCamera;

public class InnerCityArrowUpdater : MonoBehaviour
{
    public Transform UIRoot;
    public Transform arrowRoot;
    public RectTransform arrowTrans;
    
    public bool bForceUpdate = false;// 强制更新主城位置提示状态

    private RectTransform mineCanvas;
    private UnityEngine.Camera uiCamera;
    
    private string formatStr;
    private string formatStr2;
    private Vector3 m_castlePos;
    private Vector2 m_castleVec2Pos;

    private Vector2 cacheUiPos = new Vector2(-9999.0f,0f);
    private Vector3 arrowEulerAngel = Vector3.zero;
    private Vector2 uiRootPos = Vector2.zero;
    private Vector3 hitPos = Vector3.zero;

    private bool isArrowActive = true;

    public float castleOffset = 1; // 主城偏移

    private bool moveEventAdded = false;

    private bool isSetTarget = false;
    public void Init()
    {
        if (transform.parent && transform.parent.parent)
        {
            mineCanvas = transform.parent.parent.GetComponent<RectTransform>();
        }

        if (mineCanvas && mineCanvas.parent)
        {
            var uiCameraTrans = mineCanvas.parent.Find("UICamera");
            if (uiCameraTrans)
            {
                uiCamera = uiCameraTrans.GetComponent<UnityEngine.Camera>();
            }
        }

        SetArrowVisible(false);
        if (!moveEventAdded)
        {
            InnerCityCameraComponent.AddLuaMoveEventHandler(UpdateArrow);
            moveEventAdded = true;
        }
    }

    public void UnInit()
    {
        InnerCityCameraComponent.RemoveLuaMoveEventHandler(UpdateArrow);
        moveEventAdded = false;
    }

    public void SetFormatStr(string str,string str2)
    {
        formatStr = str;
        formatStr2 = str2;
    }
    
    public void SetTargetPos(Vector3 inCastlePos)
    {
        m_castlePos = inCastlePos;
        m_castleVec2Pos.x = inCastlePos.x;
        m_castleVec2Pos.y = inCastlePos.z;
        isSetTarget = true;
    }

    public void UpdateArrow(Vector2 cameraCenterPos)
    {
        if (!mineCanvas || !uiCamera || !isSetTarget)
        {
            return;
        }
        int iX = Mathf.FloorToInt(cameraCenterPos.x);
        int iY = Mathf.FloorToInt(cameraCenterPos.y);

        Vector2 selfUiPos = worldPos2UIPos(m_castlePos);
        float f_dis = Vector2.Distance(cameraCenterPos, m_castleVec2Pos) * 10;
        int distance = Mathf.RoundToInt(f_dis);
       

        float uiHalfWidth = mineCanvas.rect.width * 0.5f;
        float uiHalfHeight = mineCanvas.rect.height * 0.5f;

        bool outScreen = false;

        if (selfUiPos.x > uiHalfWidth || selfUiPos.x <-uiHalfWidth || selfUiPos.y > uiHalfHeight || selfUiPos.y < -uiHalfHeight)
        {
            if (distance > 0 && f_dis > castleOffset)
            {
                outScreen = true;
            }
        }
        
        SetArrowVisible(outScreen);

        if (outScreen)
        {
            if (Mathf.Abs(cacheUiPos.x - selfUiPos.x) > 0.01 || Mathf.Abs(cacheUiPos.y - selfUiPos.y) > 0.01 || bForceUpdate)
            {
                bForceUpdate = false;
                cacheUiPos = selfUiPos;
                Vector2 dir = selfUiPos.normalized;

                float angel = Mathf.Atan2(dir.y, dir.x) * (180 / Mathf.PI);
                angel += 90.0f;

                arrowEulerAngel.z = angel;
                arrowTrans.localEulerAngles = arrowEulerAngel;
                uiRootPos.x = UIRoot.position.x;
                uiRootPos.y = UIRoot.position.y;
                RaycastHit2D hit2D = Physics2D.Raycast(uiRootPos, dir);
              
                if (hit2D!=null && hit2D.transform!=null)
                {
                    hitPos.x = hit2D.point.x;
                    hitPos.y = hit2D.point.y;
                    hitPos.z = UIRoot.position.z;
                    arrowRoot.position = hitPos;
                }
            }
        }
    }

    /// <summary>
    /// 某些特殊的情况下，强制更新Arrow,但使用C#存储的CenterPos
    /// </summary>
    public void UpdateArrowForce()
    {
        if (WorldCameraManager.p_IsInitialize)
        {
            UpdateArrow(WorldCameraManager.GetInstance().CenterViewPosition);
        }
    }
    
    private void SetArrowVisible(bool visible)
    {
        if (isArrowActive != visible)
        {
            if (!visible)
            {
                arrowRoot.position = GlobalValue.INVISIBLE_POSITION;
                arrowRoot.localScale = Vector3.zero;
            }
            else
            {
                arrowRoot.localScale = Vector3.one;
            }
            isArrowActive = visible;
        }
    }

    public bool GetArrowVisible()
    {
        return isArrowActive;
    }

    private Vector2 worldPos2UIPos(Vector3 worldPos)
    {
        Vector3 screenPos = Vector3.zero;
        if (CityManager.Instance.mobileTouchCamera.Cam)
            screenPos = CityManager.Instance.mobileTouchCamera.Cam.WorldToScreenPoint(worldPos);

        Vector2 screenPosition = Vector2.zero;

        if (screenPos.z > 0)
        {
            screenPosition.x = screenPos.x;
            screenPosition.y = screenPos.y;
        }
        else
        {
            // 当z轴小于0时，说明城堡坐标在摄像机后方，这时方向应该取反
            screenPosition.x = -screenPos.x;
            screenPosition.y = -screenPos.y;
        }

        Vector2 uiSpacePosition = Vector2.zero;
        UnityEngine.RectTransformUtility.ScreenPointToLocalPointInRectangle(mineCanvas, screenPosition, uiCamera,
            out uiSpacePosition);
        
        return uiSpacePosition;
    }
}
